import { createRouter, createWebHistory } from "vue-router";
import ApiPublic from "@/api/public";
import routes from "./routes";

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const whiteList = ["/login"];
router.beforeEach(async (to, from, next) => {
  const user = sessionStorage.getItem("user");
  const token = (user && JSON.parse(user).token) ?? "";
  console.log("beforeEach", token);
  // 使用多语言时，可开启这段代码获取当前ip下语言环境
  // if (!sessionStorage.getItem("lang")) {
  //   await getIPInfo();
  // }
  // if (token) {
  //   if (to.path === "/login") {
  //     next("/");
  //   } else {
  //     next();
  //   }
  // } else {
  //   if (whiteList.includes(to.path)) {
  //     next();
  //   } else {
  //     next({ path: "/login", query: { redirect: to.fullPath } });
  //   }
  // }
  next();
});

const getIPInfo = async () => {
  const res = await ApiPublic.getIPInfo();
  let languages = null;
  if (res && res.languages) {
    languages = res.languages;
  } else {
    languages = navigator.language;
  }
  if (languages.indexOf("zh") != -1) {
    sessionStorage.setItem("lang", "zh");
  } else if (languages.indexOf("ja") != -1) {
    sessionStorage.setItem("lang", "ja");
  } else {
    sessionStorage.setItem("lang", "en");
  }
};

export default router;
